// 商品
const router = require('koa-router')()
const Goods = require('../models/goods')

const {auth} = require("../utils");
router.get('/', async function (ctx, next) {
    ctx.body = await Goods.find().sort({'createdAt':-1})
})

// 查询店铺商品
router.get('/:shop/:category',async function (ctx,next){
    ctx.body = await Goods.find({shop:ctx.params.shop,category:ctx.params.category})
})

// 创建商品
router.post('/', async function (ctx, next) {
    ctx.verifyParams({
        price: {type: "number", required: true},
        fmImg: {type: "string", required: true},
        category:{type: "string", required: true},
        imgArr:{type: "array", required: true},
        label:{type: "array", required: false},
        title: {type: "string", required: true},
    })
    ctx.body = await Goods.create(ctx.request.body)
})

// 修改商品信息
router.put('/:id',auth, async function (ctx, next) {
    await Goods.findByIdAndUpdate(ctx.params.id,ctx.request.body)
    ctx.body = await Goods.findById(ctx.params.id)
})

// 删除商品
router.delete('/:id',auth, async function (ctx, next) {
    let goods = await Goods.findByIdAndDelete(ctx.params.id)
    if(!goods){
        ctx.throw(404, '商品不存在');
    }
    ctx.status = 204
})

module.exports = router